package com.example.sup.controller;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sup.entity.UserInfo;
import com.example.sup.controller.request.LoginRequest;
import com.example.sup.controller.response.ServerResponse;
import com.example.sup.service.UserInfoService;
import com.example.sup.utils.RedisUtils;
import com.example.sup.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;

import static com.example.sup.constants.SupConstants.TOKEN_PREFIX;

/**
 * @ClassName LoginController
 * @Description {TODO}
 * @Author 李哲
 * @Date 15:32 2024/7/19
 * @Version 1.0
 */
@RestController
@Slf4j
public class LoginController {

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private RedisUtils redisUtil;

    @PostMapping("/user/login")
    public ServerResponse login(@RequestBody LoginRequest loginRequest){
       //1.参数检验

        //2.调用service
        QueryWrapper<UserInfo> loginWrapper = new QueryWrapper<>();
        loginWrapper.lambda().eq(UserInfo::getUserName,loginRequest.getUserName())
                .eq(UserInfo::getPassword,loginRequest.getPassword());
        UserInfo userInfo = userInfoService.getOne(loginWrapper);
        if(userInfo == null){
            return ServerResponse.failWithMsg("用户名或密码错误");
        }
        log.info("登录用户信息:{}",userInfo);
        //生产并保存token
        String token = UUID.randomUUID().toString().replace("-", "");
//        redisUtil.set(token+userInfo.getUserId(),token);//默认redis过期时间为:1天
        //数据脱敏，密码属于铭感数据
        userInfo.setPassword(null);
        userInfo.setCreateTime(null);
        userInfo.setCreateBy(null);
        userInfo.setPhone(null);
        redisUtil.set(TOKEN_PREFIX+token, Arrays.asList(userInfo));//默认redis过期时间为:1天
        log.info("登录用户的token:{}",token);
        //3.返回model--VO(登录用户信息)、token
        LoginVO loginVO = new LoginVO();
        BeanUtils.copyProperties(userInfo,loginVO);

        return ServerResponse.<LoginVO>successWithMsg(token,loginVO);
    }


}
